﻿using LoveNote.Application.Customer.Views;
using LoveNote.Application.Share;
using LoveNote.Application.Share.Login;
using LoveNote.Application.Share.Message;
using LoveNote.Database.Entities;
using LoveNote.Database.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using TookKit.Mvvm.Attributes;
using TookKit.Mvvm.Bindings;
using TookKit.Mvvm.Enums;
using TookKit.Mvvm.Events;

namespace LoveNote.Application.Customer.ViewModels
{
    [DependencyInjection(Lifetime.Singleton)]
    internal class CustomerViewModel : ObservableObject
    {
        private List<CustomerEntity> customers;
        public List<CustomerEntity> Customers
        {
            get { return customers; }
            set { SetProperty(ref customers, value); }
        }

        private CustomerEntity customer;
        public CustomerEntity Customer
        {
            get { return customer; }
            set { SetProperty(ref customer, value); }
        }

        private List<ProcessEntity> processes;
        public List<ProcessEntity> Processes
        {
            get { return processes; }
            set { SetProperty(ref processes, value); }
        }

        private string keyword;
        /// <summary>
        /// 搜索关键字
        /// </summary>
        public string Keyword
        {
            get { return keyword; }
            set { SetProperty(ref keyword, value);}
        }

        public ISession Session { get; }

        public ICommand LoadedCommand { get; }
        public ICommand UnloadedCommand { get; }
        public ICommand CreateCustomerCommand { get; }
        public ICommand UpdateCustomerAndProcessCommand { get; }
        public ICommand DeleteCustomerCommand { get; }
        public ICommand TextChangedCommand { get; } 

        private ICustomerRepository CustomerRepository { get; }
        private IProcessRepository ProcessRepository { get; }
        public CustomerViewModel(ISession session,ICustomerRepository customerRepository, IProcessRepository processRepository)
        {
            Session = session;
            CustomerRepository = customerRepository;
            ProcessRepository = processRepository;
            LoadedCommand = new RelayCommand(OnLoadedCommand);
            UnloadedCommand = new RelayCommand(OnUnloadedCommand);
            CreateCustomerCommand = new RelayCommand(OnCreateCustomerCommand);
            UpdateCustomerAndProcessCommand = new RelayCommand<CustomerEntity>(OnUpdateCustomerAndProcessCommand);
            DeleteCustomerCommand = new RelayCommand<CustomerEntity>(OnDeleteCustomerCommand);
            TextChangedCommand = new RelayCommand(OnTextChangedCommand);
        }

        /// <summary>
        /// 搜索数据
        /// </summary>
        private void OnTextChangedCommand()
        {
            if (string.IsNullOrEmpty(keyword))
            {
                LoadCustomers();
            }
            else
            {
                LoadCustomers(keyword);
            }
        }        

        private void OnDeleteCustomerCommand(CustomerEntity entity)
        {
            var result = Session.Show("是否执行当前操作？", System.Windows.MessageBoxButton.YesNo);
            if (result == null || result.Value == false)
                return;
            int count = CustomerRepository.Delete(entity);
            if (count > 0)
            {
                LoadCustomers();
            }
        }

        private void OnUpdateCustomerAndProcessCommand(CustomerEntity entity)
        {
            var view = TookKit.Mvvm.Container.Default.GetService(ViewNames.ProcessView) as ProcessView;
            var vm = view.DataContext as ProcessViewModel;
            if (vm != null && view != null)
            {
                vm.Customer = entity;
                EventBus.Default.Publish(this, new ProcessMessage(entity));//用事件去切换页面，并传递当前客户实体
            }                    
        }

        private void OnCreateCustomerCommand()
        {
            CreateCustomer();
            LoadCustomers();
        }

        private void OnUnloadedCommand()
        {
            
        }

        private void OnLoadedCommand()
        {
            LoadPrecesses();
            LoadCustomers();
        }


        /// <summary>
        /// 创建当前用户的客户
        /// </summary>
        private void CreateCustomer()
        {
            var entity = new CustomerEntity
            {
                InsertDate = DateTime.Now,
                UpdateDate= DateTime.Now,
                UserId = Session.CurrentUser.Id,
                Name = "姓名",
                Telephone = "手机号码",
                City = "城市",
                Tag = "备注"
            };
            int count = CustomerRepository.Insert(entity);
            if (count > 0)
            {
                LoadCustomers();
                Customer = entity;
            }
        }

        /// <summary>
        /// 加载当前用户的客户
        /// </summary>
        private void LoadCustomers()
        {
            Customers = CustomerRepository.GetAll()
                .FindAll(t => t.UserId == Session.CurrentUser.Id)
                .OrderByDescending(t => t.UpdateDate)
                .ToList();

            //获取每个客户最新消息
            Customers.ForEach(customer =>
            {
                customer.Process = Processes.FirstOrDefault(process => process.CustomerId == customer.Id);
            });
        }

        private void LoadCustomers(string keyword)
        {
            Customers = CustomerRepository.GetAll()
                .FindAll(t => t.UserId == Session.CurrentUser.Id && t.Name.Contains(keyword))
                .OrderByDescending(t => t.UpdateDate)
                .ToList();

            //获取每个客户最新消息
            Customers.ForEach(customer =>
            {
                customer.Process = Processes.FirstOrDefault(process => process.CustomerId == customer.Id);
            });
        }

        private void LoadPrecesses()
        {
            Processes = ProcessRepository.GetAll()
                .OrderByDescending(t => t.InsertDate)
                .ToList(); ;
        }

       
    }
}
